package chat.server;

import chat.utils.Constants;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

public class ServerReader extends Thread {
    private Socket socket;

    public ServerReader(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(socket.getInputStream());
            // 1.循环等待客户端消息
            while (true) {
                /*    2.读取当前消息类型
                      登录1    群发||@消息2   私发3       */
                int flag = dis.readInt();
                if (flag == 1) {
                    // 3.将当前socket和name存入map集合
                    String name = dis.readUTF();
                    System.out.println(name + "--->" + socket.getRemoteSocketAddress());
                    ServerChat.onLineSockets.put(socket, name);
                }
                resoleMsg(flag, dis);
            }

        } catch (Exception e) {
            System.out.println("--有人下线了--");
            // 从在线人数中将当前socket移出去
            ServerChat.onLineSockets.remove(socket);
            try {
                // 从新更新在线人数并发给所有客户端
                resoleMsg(1, dis);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }

    private void resoleMsg(int flag, DataInputStream dis) throws Exception {
        String finalMsg = null;
        if (flag == 1) {
            /** 读取所有在线人数发给所有客户端去更新自己的在线人数列表 */
            StringBuilder sb = new StringBuilder();
            Collection<String> onlineNames = ServerChat.onLineSockets.values();

            for (String name : onlineNames) {
                sb.append(name + Constants.SPILIT);
            }
            finalMsg = sb.substring(0, sb.lastIndexOf(Constants.SPILIT));

            // 将消息发送给所有客户端
            sendMsgToAll(flag, finalMsg);
        } else if (flag == 2 || flag == 3) {
            String newMsg = dis.readUTF();
            // 得到发送人
            String sendName = ServerChat.onLineSockets.get(socket);

            // 拼接内容
            StringBuilder builder = new StringBuilder();
            // 时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE");
            if (flag == 2) {
                // 读取群消息 || @消息
                builder.append(sendName).append("  ").append(sdf.format(new Date())).append("\r\n");
                builder.append("    ").append(newMsg).append("\r\n");
                sendMsgToAll(flag, builder.toString());
            } else {
                // 读取私发消息
                builder.append(sendName).append("  ").append(sdf.format(new Date())).append("对您私发\r\n");
                builder.append("    ").append(newMsg).append("\r\n");
                // 得到私发给谁
                String destName = dis.readUTF();
                sendMsgToOne(destName, builder.toString());
            }

        }
    }

    private void sendMsgToOne(String destName, String msg) throws IOException {
        // 拿到所有的在线socket管道 给这些管道写出消息
        Set<Socket> allOnLineSockets = ServerChat.onLineSockets.keySet();
        for (Socket sk : allOnLineSockets) {
            // 得到当前需要私发的socket
            // 只对这个名字对应的socket私发消息
            if (ServerChat.onLineSockets.get(sk).trim().equals(destName)) {
                DataOutputStream dos = new DataOutputStream(sk.getOutputStream());
                dos.writeInt(2); // 消息类型
                dos.writeUTF(msg);
                dos.flush();
            }
        }
    }

    private void sendMsgToAll(int flag, String msg) throws Exception {
        // 拿到所有的在线socket管道 给这些管道写出消息
        Set<Socket> allOnLineSockets = ServerChat.onLineSockets.keySet();
        for (Socket sk : allOnLineSockets) {
            DataOutputStream dos = new DataOutputStream(sk.getOutputStream());
            dos.writeInt(flag); // 消息类型
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}










